package lab3;

/**
 * Mex8 - shows how we can set up a group of threads
 * 
 * @author Anthony Varghese
 */
public class Mex8 {
	/**
	 * SimpleThread - our simple thread class
	 * - it has an "id" so that we can see it's status printed out.
	 *   and a group id
	 * @author tony
	 */
	private static class SimpleThread extends Thread{
		public SimpleThread( ThreadGroup g, String id){
			super( g, id );
		}
		public void run(){
			System.out.println("   Thread " + getThreadGroup() + ":" + getName() + " starting ...");
			int i = 0;
			while ( true ){
				i++;
				try {
					sleep(100);
				} catch (InterruptedException e) {
					System.out.println("   ... thread " + getThreadGroup() + ":" + getName() + " done!");
					return;
				}
			}
		}
	}
	
	/**
	 * main - main method for Mex8
	 * @param args
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws InterruptedException {
		System.out.println("Mex8 program starting ...");
		ThreadGroup group1 = new ThreadGroup( "Main Group" );
		for (int i=0; i<5; i++){
			SimpleThread t = new SimpleThread( group1, "m"+i );
			t.start();
		}

		// We will also set up two sub-groups under group1:
		ThreadGroup groupx = new ThreadGroup( group1, "Sub-group x" );
		ThreadGroup groupy = new ThreadGroup( group1, "Sub-group y" );
		for (int i=0; i<7; i++)
			(new SimpleThread( groupx, "x"+i )).start();
		for (int i=0; i<3; i++)
			(new SimpleThread( groupy, "y"+i )).start();

		
		// Wait a few seconds
		Thread.sleep(2000);
		
		// list the threads in the group and interrupt them
		System.out.println(" " + group1.getName() + " has :" );
		group1.list();
		
		// create an array of threads in group - so that we can
		//   join them all later
		Thread g1[] = new Thread[group1.activeCount()];
		group1.enumerate(g1);

		System.out.println("\n Interrupting all threads in " + group1.getName() );
		group1.interrupt();
		
		// wait for all threads to be done:
		for (Thread t : g1)
			t.join();
		System.out.println(" after the joins, number of active threads is " + group1.activeCount() );
		System.out.println("... program done!");
	}
}